package com.fcscs.cservice.communication.mail;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fcscs.cservice.communication.CommIntfAdaptor;
import com.fcscs.share.model.EmailModel;
import com.fcscs.share.service.EmailManager;

@Service("mailAdaptor")
public class MailAdaptor implements CommIntfAdaptor {

	@Autowired
	EmailManager emailMgr;

	@Override
	public byte[] transport(byte[] data, Map<CommParam, Serializable> params) {
		EmailModel model = new EmailModel();
		try {
			model.setEmailContext(new String(data));
			model.setEmailSubject((String)params.get(CommParam.TITLE));
			model.setToEmailList(parseEmailList((String)params.get(CommParam.DEVICE)));
			emailMgr.send(model);
			return data;
		} catch (Exception ex) {
			return null;
		}
	}

	static List<String> parseEmailList(String mails) {
		String[] arr = mails.split("; *");
		List<String> list = new ArrayList<String>();
		for (String s : arr) {
			list.add(s.trim());
		}
		return list;
	}
}
